<?php
/*
企悦内微信相关功能控制器

*/
include_once(ROOTDIR.'include/wx.class.php');
class Weixin_con extends Wx{
	//回复图文操作
	
	//用户关注自动回复
	public function rreg(){
		if(empty($this->userinfo)){Lxbase::gologin();}
		if(!empty($_POST)){
			$type=intval($_POST["type"]);
			$id=intval($_POST["id"]);
			if($type==1){
				$content=$_POST["content"];
				$mode=1;
				if(empty($content)){die(jsfshow("文字不能为空"));}
			}elseif($type==2){
				//添加图片
				if(!empty($_FILES["img"]["size"])){
					//如果是直接添加则先生成资源
					$tempurl = $this->settempfile($_FILES["img"]);
					$ret = $this->setmedia($tempurl,"image");
					if(is_array($ret)){
						die(jsfshow($ret["errmsg"]));
					}else{
						$media_id=$ret;
						if(is_array($media)){
							die(jsfshow('生成微信素材失败，请重试'));
						}
						//同步微信素材
						$picdata = $this->upload($_FILES["img"],'wxrequest');
						if(empty($picdata)){die(jsfshow('同步素材失败，请重试'));}
						$picurl=$picdata["pic"];
						//资源入库
						$this->setdata("wxmedia","userid={$this->userinfo['userid']},media_id='{$media_id}',type='img',title='关注图片',content='关注后自动回复的图片',url='{$picurl}',tim=now()");
					}
				}elseif(!empty($_POST["media_id2"])){
					$media_id=$_POST["media_id2"];
					$picurl=$_POST["url2"];
					$ishave = $this->viewdata("id","wxmedia","where media_id='{$media_id}'");
					if(empty($ishave)){
						die(jsfshow("无效的资源ID"));
					}
				}else{
					die(jsfshow("请上传图片或选择图片素材"));
				}
				$content=$media_id;
				$mode=2;
			}elseif($type==3){
				//添加语音
				$media_id = $_POST["media_id3"];
				if(!empty($_FILES["voice"]["size"])){
					//如果是直接添加则先生成资源
						$title=$_POST["title"];
						if(empty($title)){die(jsfshow('请填写语音标题'));}
						$tempurl = $this->settempfile($_FILES["voice"]);
						$ret = $this->setmedia($tempurl,"voice");
						if(is_array($ret)){
							die(jsfshow($ret["errmsg"]));
						}
						$media_id=$ret;
						//同步微信素材
						$picdata = $this->upload($_FILES["voice"],'wxrequest');
						if(empty($picdata)){die(jsfshow('同步素材失败，请重试'));}
						$picurl=$picdata["pic"];
						//资源入库
						$this->setdata("wxmedia","userid={$this->userinfo['userid']},media_id='{$media_id}',type='voice',title='{$title}',content='关注自动回复的语音',url='{$picurl}',tim=now()");
				}elseif(!empty($media_id)){
						//如果是选定资源查询资源是否可用
						$picurl=$_POST["url3"];
						$ishave = $this->viewdata("id","wxmedia","where media_id='{$media_id}'");
						if(empty($ishave)){die(jsfshow('无效的资源'));}
				}else{
					die(jsfshow('回复语音消息需要上传或选定语音素材'));
				}
				$content=$media_id;
				$mode=3;
			}elseif($type==4){
				//添加视频
				$media_id = $_POST["media_id4"];
				if(!empty($_FILES["video"]["size"])){
					//如果是直接添加则先生成资源
					$title=$_POST["tit"];
					$desc = $_POST["desc"];
					if(empty($title) || empty($desc)){die(jsfshow('请填写视频标题与视频说明'));}
					if(empty($_FILES["video"]["size"])){die(jsfshow('上传文件错误，请检查后再上传'));}
					$tempurl = $this->settempfile($_FILES["video"]);
					$data["file"]=$tempurl;
					$data["title"]=$title;
					$data["desc"]=$desc;
					$ret = $this->setmedia($data,"video");
					if(is_array($ret)){die(jsfshow($ret["errmsg"]));}
					$media_id=$ret;
					//同步微信素材
					$picdata = $this->upload($_FILES["video"],'wxrequest');
					if(empty($picdata)){die(jsfshow('同步素材失败，请重试'));}
					$picurl=$picdata["pic"];
					//资源入库
					$this->setdata("wxmedia","userid={$this->userinfo['userid']},media_id='{$media_id}',type='video',title='{$title}',content='{$desc}',url='{$picurl}',tim=now()");
				}elseif(!empty($media_id)){
					//如果是选定资源查询资源是否可用
					$picurl=$_POST["url4"];
					$ishave = $this->viewdata("id,url","wxmedia","where media_id='{$media_id}'");
					if(empty($ishave)){
						die(jsfshow('无效的资源'));
					}
					$picurl = $ishave["url"];
				}else{
					die(jsfshow('回复视频消息需要上传或选定视频素材'));
				}
				$content=$media_id;
				$mode=4;
			}else{
				die(jsfshow('请选择自动回复的类型'));
			}
			$ishave = $this->viewdata("id","wxrequest","where userid={$this->userinfo['userid']} and mode={$mode} and type=9");
			if(empty($ishave)){
				$this->setdata("wxrequest","userid={$this->userinfo['userid']},title='关注自动回复',tkey='',content='{$content}',mode={$mode},type=9");
			}else{
				$this->updata("wxrequest","content='{$content}'","where id={$ishave['id']}");
			}
			if($mode>1){
				die("<script>parent.showwxrequest({$mode},'{$picurl}');alert('自动回复设置成功')</script>");
			}else{
				die("<script>alert('自动回复设置成功')</script>");
			}
		}else{
			$iswxputdone = $this->viewdata("id","wxuser","where userid={$this->userinfo['userid']}");
			if(empty($iswxputdone)){die("<script>location.href='".$this->basehost."index.php?g=user&m=member&a=company&selnum=wx'</script>");}
			$list = $this->arrdata("*","wxrequest","where userid={$this->userinfo['userid']} and type=9");
			foreach($list as $k=>$v){
				if($list[$k]["mode"]==1){
					$view["text"]=$list[$k];
				}elseif($list[$k]["mode"]==2){
					$view["img"]=$list[$k];
					$media_id=$list[$k]["content"];
					$view["img"]["url"] = $this->oncedata("url","wxmedia","where media_id='{$media_id}'");
				}elseif($list[$k]["mode"]==3){
					$view["voice"]=$list[$k];
					$media_id=$list[$k]["content"];
					$view["voice"]["url"]=$this->oncedata("url","wxmedia","where media_id='{$media_id}'");
				}elseif($list[$k]["mode"]==4){
					$view["video"]=$list[$k];
					$media_id=$list[$k]["content"];
					$view["video"]["url"] = $this->oncedata("url","wxmedia","where media_id='{$media_id}'");
				}
			}
			$this->smarty->assign("view",$view);
			$this->smarty->display("wx_re_reg.tpl");
		}
	}
	
	//用户其他消息自动回复
	public function rmsg(){
		if(empty($this->userinfo)){Lxbase::gologin();}
		if(!empty($_POST)){
			$type=intval($_POST["type"]);
			if($type==1){
				$content=$_POST["content"];
				$mode=1;
				if(empty($content)){die(jsfshow("文字不能为空"));}
			}elseif($type==2){
				//添加图片
				if(!empty($_FILES["img"]["size"])){
					//如果是直接添加则先生成资源
					$tempurl = $this->settempfile($_FILES["img"]);
					$ret = $this->setmedia($tempurl,"image");
					if(is_array($ret)){
						die(jsfshow($ret["errmsg"]));
					}else{
						$media_id=$ret;
						//同步微信素材
						$picdata = $this->upload($_FILES["img"],'wxrequest');
						if(empty($picdata)){die(jsfshow('同步素材失败，请重试'));}
						$picurl=$picdata["pic"];
						//资源入库
						$this->setdata("wxmedia","userid={$this->userinfo['userid']},media_id='{$media_id}',type='img',title='关注图片',content='关注后自动回复的图片',url='{$picurl}',tim=now()");
					}
				}elseif(!empty($_POST["media_id2"])){
					$media_id=$_POST["media_id2"];
					$picurl=$_POST["url2"];
					$ishave = $this->viewdata("id","wxmedia","where media_id='{$media_id}'");
					if(empty($ishave)){die(jsfshow("无效的资源ID"));}
				}else{
					die(jsfshow("请上传图片或选择图片素材"));
				}
				$content=$media_id;
				$mode=2;
			}elseif($type==3){
				//添加语音
				$media_id = $_POST["media_id3"];
				if(!empty($_FILES["voice"]["size"])){
					//如果是直接添加则先生成资源
					$title=$_POST["title"];
					if(empty($title)){die(jsfshow('请填写语音标题'));}
						$tempurl = $this->settempfile($_FILES["voice"]);
						$ret = $this->setmedia($tempurl,"voice");
						if(is_array($ret)){die(jsfshow($ret["errmsg"]));}
						$media_id=$ret;
						//同步微信素材
						$picdata = $this->upload($_FILES["voice"],'wxrequest');
						if(empty($picdata)){die(jsfshow('同步素材失败，请重试'));}
						$picurl=$picdata["pic"];
						//资源入库
						$this->setdata("wxmedia","userid={$this->userinfo['userid']},media_id='{$media_id}',type='voice',title='{$title}',content='关注自动回复的语音',url='{$picurl}',tim=now()");
				}elseif(!empty($media_id)){
						//如果是选定资源查询资源是否可用
						$picurl=$_POST["url3"];
						$ishave = $this->viewdata("id","wxmedia","where media_id='{$media_id}' and userid={$this->userinfo['userid']}");
						if(empty($ishave)){die(jsfshow('无效的资源'));}
				}else{
					die(jsfshow('回复语音消息需要上传或选定语音素材'));
				}
				$content=$media_id;
				$mode=3;
			}elseif($type==4){
				//添加视频
				$media_id = $_POST["media_id4"];
				if(!empty($_FILES["video"]["size"])){
					//如果是直接添加则先生成资源
					$title=$_POST["tit"];
					$desc = $_POST["desc"];
					if(empty($title) || empty($desc)){die(jsfshow('请填写视频标题与视频说明'));}
					$tempurl = $this->settempfile($_FILES["video"]);
					$data["file"]=$tempurl;
					$data["title"]=$title;
					$data["desc"]=$desc;
					$ret = $this->setmedia($data,"video");
					if(is_array($ret)){
						die(jsfshow($ret["errmsg"]));
					}
					$media_id=$ret;
					//同步微信素材
						$picdata = $this->upload($_FILES["video"],'wxrequest');
						if(empty($picdata)){die(jsfshow('同步素材失败，请重试'));}
						$picurl=$picdata["pic"];
					//资源入库
					$this->setdata("wxmedia","userid={$this->userinfo['userid']},media_id='{$media_id}',type='video',title='{$title}',content='{$desc}',url='{$picurl}',tim=now()");
				}elseif(!empty($media_id)){
					//如果是选定资源查询资源是否可用
					$picurl=$_POST["url4"];
					$ishave = $this->viewdata("id,url","wxmedia","where media_id='{$media_id}' and userid={$this->userinfo['userid']}");
					if(empty($ishave)){
						die(jsfshow('无效的资源'));
					}
					$picurl = $ishave["url"];
				}else{
					die(jsfshow('回复视频消息需要上传或选定视频素材'));
				}
				$content=$media_id;
				$mode=4;
			}else{
				die(jsfshow('请选择自动回复的类型'));
			}
			$ishave = $this->viewdata("id","wxrequest","where userid={$this->userinfo['userid']} and mode={$mode} and type=8");
			if(empty($ishave)){
				$this->setdata("wxrequest","userid={$this->userinfo['userid']},title='默认自动回复',tkey='',content='{$content}',mode={$mode},type=8");
			}else{
				$this->updata("wxrequest","content='{$content}'","where id={$ishave['id']}");
			}
			if($mode>1){
				die("<script>parent.showwxrequest({$mode},'{$picurl}');alert('自动回复设置成功')</script>");
			}else{
				die("<script>alert('自动回复设置成功')</script>");
			}
		}else{
			$iswxputdone = $this->viewdata("id","wxuser","where userid={$this->userinfo['userid']}");
			if(empty($iswxputdone)){die("<script>location.href='".$this->basehost."index.php?g=user&m=member&a=company&selnum=wx'</script>");}
			$list = $this->arrdata("*","wxrequest","where userid={$this->userinfo['userid']} and type=8");
			foreach($list as $k=>$v){
				if($list[$k]["mode"]==1){
					$view["text"]=$list[$k];
				}elseif($list[$k]["mode"]==2){
					$view["img"]=$list[$k];
					$media_id=$list[$k]["content"];
					$view["img"]["url"] = $this->oncedata("url","wxmedia","where media_id='{$media_id}'");
				}elseif($list[$k]["mode"]==3){
					$view["voice"]=$list[$k];
					$media_id=$list[$k]["content"];
					$view["voice"]["url"]=$this->oncedata("url","wxmedia","where media_id='{$media_id}'");
				}elseif($list[$k]["mode"]==4){
					$view["video"]=$list[$k];
					$media_id=$list[$k]["content"];
					$view["video"]["url"] = $this->oncedata("url","wxmedia","where media_id='{$media_id}'");
				}
			}
			$this->smarty->assign("view",$view);
			$this->smarty->display("wx_re_msg.tpl");
		}
	}
	
	
	//用户自定义回复规则
	public function rsmart(){
		if(empty($this->userinfo)){Lxbase::gologin();}
		if(!empty($_POST)){
			$rtxt=$_POST["rtxt"];
			$rmedia=$_POST["rmedia"];
			$tkey=$_POST["tkey"];
			$tmode=$_POST["mode"];
			$title=$_POST["title"];
			$id=intval($_POST["id"]);
			$isall = empty($_POST["isall"])?0:intval($_POST["isall"]);
			if(empty($title)){
				die(jsfshow('请填写规则名称'));
			}
			if(empty($tkey) || (empty($rtxt) && empty($rmedia))){
				die(jsfshow('请设置关键词与回复内容'));
			}
			foreach($tkey as $k=>$v){
				if(empty($tmode[$k])){
					$mode=0;
				}else{
					$mode=1;
				}
				$into="tkey='{$tkey[$k]}',mode={$mode}";
				$keyid[] = $this->setdata("wxrequest_info",$into);
			}
			foreach($rtxt as $k=>$v){
				$rtxt[$k]=str_replace('\\\\n','',$v);
			}
			$temp["txt"] = $rtxt;
			$temp["media"] = $rmedia;
			$content = serialize($temp);
			$tkey=implode(",",$keyid);
			if(!empty($id)){
				$into="title='{$title}',tkey='{$tkey}',content='{$content}',mode={$isall}";
				$this->updata("wxrequest",$into,"where id={$id}");
			}else{
				$into="userid={$this->userinfo['userid']},title='{$title}',tkey='{$tkey}',content='{$content}',mode={$isall},type=7";
				$this->setdata("wxrequest",$into);
			}
			die("<script>alert('回复规则设置成功');parent.location.href='?g=wx&m=weixin&a=rsmart';</script>");
		}else{
			$iswxputdone = $this->viewdata("id","wxuser","where userid={$this->userinfo['userid']}");
			if(empty($iswxputdone)){die("<script>location.href='".$this->basehost."index.php?g=user&m=member&a=company&selnum=wx'</script>");}
			$list = $this->arrdata("*","wxrequest","where userid={$this->userinfo['userid']} and type=7");
			foreach($list as $k=>$v){
				$temp = unserialize($list[$k]["content"]);
				$list[$k]["txt"] = $temp["txt"];
				$list[$k]["tnum"]=count($temp["txt"]);
				$marr = $temp["media"];
				$mediainfo=array();
				if(!empty($marr)){
					foreach($marr as $kk=>$vv){
						$mediainfo[] = $this->viewdata("*","wxmedia","where media_id='{$vv}'");
					}
				}
				$list[$k]["media"] = $mediainfo;
				$list[$k]["inum"] = $list[$k]["vnum"] = $list[$k]["dnum"] = $list[$k]["nnum"] = 0;
				if(!empty($mediainfo)){
					foreach($mediainfo as $kk=>$vv){
						if($mediainfo[$kk]["type"]=='img'){
							$list[$k]["inum"]+=1;
						}elseif($mediainfo[$kk]["type"]=='voice'){
							$list[$k]["vnum"]+=1;
						}elseif($mediainfo[$kk]["type"]=='video'){
							$list[$k]["dnum"]+=1;
						}elseif($mediainfo[$kk]["type"]=='news'){
							$list[$k]["nnum"]+=1;
						}
					}
				}
				$list[$k]["allnum"] = $list[$k]["tnum"] + $list[$k]["inum"] + $list[$k]["vnum"] + $list[$k]["dnum"] + $list[$k]["nnum"];
				$list[$k]["keylist"] = $this->arrdata("*","wxrequest_info","where id IN({$list[$k]['tkey']})");
			}
			$this->smarty->assign("list",$list);
			$this->smarty->display("wx_re_smart.tpl");
		}
	}
	
	//删除自动回复
	public function delrequest($id,$type){
		if(empty($this->userinfo)){Lxbase::gologin();}
		$id=intval($_GET["id"]);
		$type=$_GET["type"];
		if(empty($id)){die(jsfshow('参数ID错误'));}
		$view = $this->viewdata("id,userid","wxrequest","where id={$id}");
		if($this->userid != $view["userid"]){
			die(jsfshow('用户资料错误'));
		}
		$this->deldata("wxrequest","where id={$id}");
		echo jsfunc('gourl',array('?g=wx&m=weixin&a='.$type,'删除成功'));
		exit;
	}
	
	//素材管理
	public function mediashow(){
		if(empty($this->userinfo)){Lxbase::gologin();}
		$id=intval($_POST["id"]);
		if(!empty($id)){
			$view = $this->viewdata("*","wxmedia","where id={$id} and userid={$this->userinfo['userid']}");
			if(empty($view)){
				die(jsfshow('用户身份验证失败,不能管理该素材'));
			}
			$this->smarty->assign("view",$view);
			$this->smarty->display("mediaview.tpl");
		}else{
			$list = $this->arrdata("*","wxmedia","where userid={$this->userinfo['userid']}");
			$this->smarty->assign("list",$list);
			$this->smarty->display("medialist.tpl");
		}
	}
	
	//添加素材
	public function addmedia(){
		if(empty($this->userinfo)){Lxbase::gologin();}
		$type=$_POST["type"];
		if($type=='news'){
			//单页图文素材
			$data["title"]=$_POST["title"];
			$data["thumb_media_id"]=$_POST["thumb"];
			if(!empty($thumb)){
				$ishave = $this->viewdata("*","wxmedia","where media_id='{$thumb}'");
				if(empty($ishave)){
					die(jsfshow('封面素材ID错误'));
				}
			}elseif(!empty($_FILES["media"]["size"])){
				//如果没有素材则新添素材
				$ret = $this->setmedia($_FILES["media"]["tmp_name"],"image");
				if(is_array($ret)){
					die(jsfshow($ret["errmsg"]));
				}else{
					$data["thumb_media_id"]=$ret;
				}
			}else{
				die(jsfshow('请选择或上传素材'));
				
			}
			$data["author"] = $_POST["author"];
			$data["digest"] = $_POST["digest"];
			$data["content"]=$_POST["content"];
			$data["content_source_url"]=$_POST["url"];
			$data["show_cover_pic"] = intval($_POST["ishowpic"]);
			$ret = $this->setmedia($data);
			if(is_array($ret)){
				die(jsfshow($ret["errmsg"]));
			}else{
				$this->setdata("wxmedia","userid={$this->userinfo['userid']},media_id='{$media_id}',title='".$data["title"]."',content='".$data["content"]."',tim=now()");
			}
		}elseif($type='allnews'){
			//多条图文素材 最多8条
			$file=$_FILES["media"];
			$titlearr = $_POST["title"];
			$thumbarr = $_POST["thumb"];
			$authorarr = $_POST["author"];
			$digestarr = $_POST["digest"];
			$ispicarr = $_POST["ispicarr"];
			$contentarr = $_POST["content"];
			$urlarr = $_POST["url"];
			for($i=0;$i<8;$i++){
				if(empty($titlearr[$i]) || empty($contentarr[$i])){
					continue;
				}else{
					$data[$i]["title"]=$titlearr[$i];
					if(!empty($thumbarr[$i])){
						$ishave = $this->viewdata("id","wxmedia","where media_id='{$thumbarr[$i]}'");
						if(empty($ishave)){
							die(jsfshow('第'.($i+1)."条图文封面素材ID错误"));
						}
					}elseif(!empty($file["size"][$i])){
						$ret = $this->setmedia($file["tmp_name"][$i],"image");
						if(is_array($ret)){
							die(jsfshow($ret["errmsg"]));
						}else{
							$data[$i]["thumb_media_id"]=$ret;
						}
					}else{
						die(jsfshow('请上传或选择第'.($i+1)."条图文封面图片"));
					}
					$data[$i]["author"] = $authorarr[$i];
					$data[$i]["digest"] = $digestarr[$i];
					$data[$i]["content"] = $content[$i];
					$data[$i]["content_source_url"]=$urlarr[$i];
					$data[$i]["show_cover_pic"] = intval($ispicarr[$i]);
				}
			}
			$ret = $this->setmedia($data);
			if(is_array($ret)){
				die(jsfshow($ret["errmsg"]));
			}else{
				$content = unserialize($data);
				$this->setdata("wxmedia","userid={$this->userinfo['userid']},media_id={$ret},title='".$data[0]["title"]."等图文',content='{$content}'");
			}
		}else{
			//其他多媒体素材 支持image voice video
			if(empty($_FILES["media"]["size"])){
				die(jsfshow('请上传有效的资源文件'));
			}
			$ret = $this->setmedia($_FILES["media"]["tmp_name"],$type);
			if(is_array($ret)){
				die(jsfshow($ret["errmsg"]));
			}else{
				$this->setdata("wxmedia","userid={$this->userinfo['userid']},media_id={$ret}");
			}
		}
	}
	//删除站内素材 同步删除微信素材库
	public function delmedia(){
		if(empty($this->userinfo)){die(json_encode(array("error"=>1009,"msg"=>"登陆状态已失效，请重新登陆")));}
		$id=intval($_GET["id"]);
		if(empty($id)){
			die(json_encode(array("error"=>1001,"msg"=>"素材参数错误")));
		}
		$view = $this->viewdata("*","wxmedia","where id={$id}");
		if(empty($view)){
			die(json_encode(array("error"=>1002,"msg"=>"素材获取错误")));
		}
		if($this->userinfo["userid"] != $view["userid"]){
			die(json_encode(array("error"=>1003,"msg"=>"素材权限错误")));
		}
		$ret = $this->delwxmedia($view["media_id"]);
		$this->deldata("wxmedia","where id={$id}");
		die(json_encode(array("error"=>1000,"msg"=>"删除素材成功")));
	}
	
	//获得用户分组
	public function wxgroup(){
		$group = $this->getwxgroup();
		if(!empty($group["errmsg"])){
			return '';
		}else{
			return $group;
		}
	}
	
	//群发管理
	public function wxsend(){
		if(empty($this->userinfo)){Lxbase::gologin();}
		if(!empty($_POST)){
			$sendtype=intval($_POST["sendtype"]);
			if($sendtype==2){
				$groupid=intval($_POST["groupid"]);
				$sel=$groupid;
			}elseif($sendtype==3){
				$fenname=$_POST["fenname"];
				$sel=$fenname;
			}else{
				$sel='';
			}
			$type=intval($_POST["type"]);
			$typearr=array(1=>"image",3=>"voice",4=>"video",5=>"news");
			if($type>1){
				$media_id=$_POST["media_id{$type}"];
				if($type==4){
					$view=$this->viewdata("*","wxmedia","where media_id='{$media_id}'");
					$title=$view["title"];
					$desc=$view["desc"];
					$content["media_id"]=$media_id;
					$content["title"]=$title;
					$content["desc"]=$desc;
				}else{
					$content=$media_id;
				}
			}else{
				$content=$_POST["content"];
			}
			$mptype=$typearr[$type];
			if($this->wxsendall($sel,$mptype,$content)){
			}else{
				
			}
			
		}
		$iswxputdone = $this->viewdata("id","wxuser","where userid={$this->userinfo['userid']}");
		if(empty($iswxputdone)){die("<script>location.href='".$this->basehost."index.php?g=user&m=member&a=company&selnum=wx'</script>");}
		$list=$this->arrdata("*","wxsend","where userid={$this->userinfo['userid']}");
		$group = $this->wxgroup();
		$this->smarty->assign("group",$group);
		$this->smarty->assign("list",$list);
		$this->smarty->display("sendwx");
	}
	
	//微信菜单编辑
	public function wxmenu(){
		if(empty($this->userinfo)){Lxbase::gologin();}
		$iswxputdone = $this->viewdata("id","wxuser","where userid={$this->userinfo['userid']}");
		if(empty($iswxputdone)){die("<script>location.href='".$this->basehost."index.php?g=user&m=member&a=company&selnum=wx'</script>");}
		$view = $this->viewdata("*","wxmenu","where userid={$this->userinfo['userid']}");
		if(!empty($view)){
			$btitle = unserialize($view["btitle"]);
			$btype = unserialize($view["btype"]);
			$bcon = unserialize($view["bcon"]);
			$stitle=unserialize($view["stitle"]);
			$stype = unserialize($view["stype"]);
			$scon = unserialize($view["scon"]);
			$j=0;
			for($i=1;$i<4;$i++){
				$m=0;
				if(!empty($btitle)){
					$data[$i]["title"] = str_replace(" ","&nbsp;",array_shift($btitle));
				}
				if(!empty($data[$i]["title"])){
					$j++;	
				}
				if(!empty($btype[$i])){$data[$i]["type"] = $btype[$i];}
				if(!empty($bcon[$i])){$data[$i]["con"] = $bcon[$i];}
				if(!empty($stype[$i])){$data[$i]["stype"] = $stype[$i];}
				if(!empty($stitle[$i])){$data[$i]["stitle"] = $stitle[$i];}
				if(!empty($data[$i]["stitle"])){
					foreach($data[$i]["stitle"] as $v){
						if(!empty($v)){
							$m++;
						}
					}
				}
				$data[$i]["stnum"]=$m;
				if(!empty($scon[$i])){$data[$i]["scon"] = $scon[$i];}
			}
			$this->smarty->assign("view",$data);
		}
		$this->smarty->assign("titlenum",$j);
		$this->smarty->display("wx_menu.tpl");
	}
	
	//删除关注回复
	public function delreg(){
		if(empty($this->userinfo)){die(json_encode(array("error"=>1009,"msg"=>"登陆状态已失效，请重新登陆")));}
		$type=$_GET["type"];
		$this->deldata("wxrequest","where userid={$this->userinfo['userid']} and type=9 and mode={$type}");
		echo json_encode(array('error'=>1000,'msg'=>'删除成功'));
		exit;
	}
	//删除默认回复
	public function delmsg(){
		if(empty($this->userinfo)){die(json_encode(array("error"=>1009,"msg"=>"登陆状态已失效，请重新登陆")));}
		$type=$_GET["type"];
		$this->deldata("wxrequest","where userid={$this->userinfo['userid']} and type=8 and mode={$type}");
		echo json_encode(array('error'=>1000,'msg'=>'删除成功'));
		exit;
	}
	
	//删除规则回复
	public function delsmart(){
		if(empty($this->userinfo)){die(json_encode(array("error"=>1009,"msg"=>"登陆状态已失效，请重新登陆")));}
		$id=intval($_GET["id"]);
		$userid=$this->userinfo["userid"];
		$view = $this->viewdata("*","wxrequest","where userid={$this->userinfo['userid']} and type=7 and id={$id}");
		if(empty($view)){
			die(json_encode(array("error"=>1001,"msg"=>"信息标识错误")));
		}
		$tkeylist = explode(",",$view["tkey"]);
		foreach($tkeylist as $v){
			$this->deldata("wxrequest_info","where id={$v}");
		}
		$this->deldata("wxrequest","where id={$id}");
		echo json_encode(array("error"=>1000,"msg"=>"删除成功"));
		exit;
	}
	
	
	//AJAX保存资源
	public function savesmart(){
		if(empty($this->userinfo)){die(json_encode(array("error"=>1009,"msg"=>"登陆状态已失效，请重新登陆")));}
		$type=intval($_POST["type"]);
		if($type==1){
			$content=$_POST["content"];
		}elseif($type==2){
			//添加图片
			if(!empty($_FILES["img"])){
				if(empty($_FILES["img"]["size"])){
					echo json_encode(array("error"=>1001,"msg"=>"上传文件错误，请检查后再上传"));
					exit;
				}
				$tempurl = $this->settempfile($_FILES["img"]);
				$ret = $this->setmedia($tempurl,"image");
				if(is_array($ret)){
					echo json_encode(array("error"=>1005,"msg"=>$res["errmsg"]));
					exit;
				}else{
					$media_id=$ret;
					if(is_array($media)){
						echo json_encode(array("error"=>1002,"msg"=>"生成微信素材失败，请重试"));
						exit;
					}
					//同步微信素材
					$picdata = $this->upload($_FILES["img"],'wxrequest');
					if(empty($picdata)){
						echo json_encode(array("error"=>1003,"msg"=>"同步素材失败，请重试"));
						exit;
					}
					$picurl=$picdata["pic"];
					//资源入库
					$newid = $this->setdata("wxmedia","userid={$this->userinfo['userid']},media_id='{$media_id}',type='img',title='规则回复图片',content='规则回复图片',url='{$picurl}',tim=now()");
				}
			}else{
				echo json_encode(array("error"=>1004,"msg"=>"请上传图片文件"));
				exit;
			}
			$content=$media_id;
		}elseif($type==3){
			$vtit=$_POST["title"];
			if(empty($vtit)){echo json_encode(array("error"=>1006,"msg"=>"请填写语音标题"));exit;}
				//添加语音
				$media_id = $_POST["media_id"];
				if(!empty($_FILES["voice"])){
					if(empty($_FILES["voice"]["size"])){
							echo json_encode(array("error"=>1001,"msg"=>"上传文件错误，请检查后再上传"));
							exit;
						}
					if($_FILES["voice"]["size"]>5000000){
							echo json_encode(array("error"=>1007,"msg"=>"音频文件超大，请上传小于5M的音频文件"));
							exit;
						}
						$tempurl = $this->settempfile($_FILES["voice"]);
						$ret = $this->setmedia($tempurl,"voice");
						if(is_array($ret)){
							echo json_encode(array("error"=>1005,"msg"=>$ret["errmsg"]));
							exit;
						}
						$media_id=$ret;
						//同步微信素材
						$picdata = $this->upload($_FILES["voice"],'wxrequest');
						if(empty($picdata)){
							echo json_encode(array("error"=>1003,"msg"=>"同步素材失败，请重试"));
							exit;
						}
						$picurl=$picdata["pic"];
						//资源入库
						$newid = $this->setdata("wxmedia","userid={$this->userinfo['userid']},media_id='{$media_id}',type='voice',title='{$vtit}',content='规则回复语音',url='{$picurl}',tim=now()");
				}else{
					echo json_encode(array("error"=>1004,"msg"=>"请上传语音文件"));
					exit;
				}
				$content=$media_id;
		}elseif($type==4){
			//添加视频
				$tit = $_POST["title"];
				$desc = $_POST["desc"];
				if(empty($tit) || empty($desc)){
					echo json_encode(array("error"=>1006,"msg"=>"请填写视频标题与说明"));
					exit;
				}
				if(!empty($_FILES["video"])){
					//如果是直接添加则先生成资源
					if(empty($_FILES["video"]["size"])){
						echo json_encode(array("error"=>1001,"msg"=>"上传文件错误，请检查后再上传"));
						exit;
					}
					if($_FILES["video"]["size"]>15000000){
						echo json_encode(array("error"=>1007,"msg"=>"上传文件太大，请上传小于15M的视频文件"));
						exit;
					}
					$tempurl = $this->settempfile($_FILES["video"]);
					$data["file"]=$tempurl;
					$data["title"]=$tit;
					$data["desc"]=$desc;
					$ret = $this->setmedia($data,"video");
					if(is_array($ret)){
						echo json_encode(array("error"=>1005,"msg"=>$res["errmsg"]));
						exit;
					}
					$media_id=$ret;
					//同步微信素材
					$picdata = $this->upload($_FILES["video"],'wxrequest');
					if(empty($picdata)){
						echo json_encode(array("error"=>1003,"msg"=>"同步素材失败，请重试"));
						exit;
					}
					$picurl=$picdata["pic"];
					//资源入库
					$newid = $this->setdata("wxmedia","userid={$this->userinfo['userid']},media_id='{$media_id}',type='video',title='{$tit}',content='{$desc}',url='{$picurl}',tim=now()");
				}else{
					echo json_encode(array("error"=>1004,"msg"=>"请上传视频文件"));
					exit;
				}
				$content=$media_id;
		}else{
			echo json_encode(array("error"=>1006,"msg"=>"类型错误"));
			exit;
		}
		//素材同步建立完成后返回到前台
		$rdata["error"]=1000;
		if($type>1){
			$rdata["msg"]=$picurl;
			$rdata["media_id"]=$media_id;
			$rdata["mid"]=$newid;
		}else{
			$rdata["msg"]=$content;
		}
		$rdata["type"]=$type;
		echo json_encode($rdata);
		exit;
	}
	
	//获得某规则内的回复内容
	public function getwxrbyid(){
		if(empty($this->userinfo)){die(json_encode(array("error"=>1009,"msg"=>"登陆状态已失效，请重新登陆")));}
		$id=intval($_GET["id"]);
		$view = $this->viewdata("*","wxrequest","where id={$id}");
		if(empty($view)){
			echo json_encode(array("error"=>1001,"msg"=>"错误的资源ID"));
			exit;
		}
		$temp = unserialize($view["content"]);
		$view["media"]["txt"] = $temp["txt"];
		$view["tnum"] = $view["inum"] = $view["vnum"] = $view["dnum"] = $view["nnum"] = 0;
		$view["tnum"]=count($view["media"]["txt"]);
		$mediainfo = $temp["media"];
		if(!empty($mediainfo)){
			foreach($mediainfo as $v){
				$temp = $this->viewdata("*","wxmedia","where media_id='{$v}'");
				if($temp["type"]=='news'){
					$content = unserialize(base64_decode($temp["content"]));
					if(!empty($content)){
						$tempinfo = array_shift($content["articles"]);
					}
					$temp["ntitle"] = $tempinfo["title"];
					$temp["url"] = $this->oncedata("url","wxmedia","where media_id='".$tempinfo["thumb_media_id"]."'");
				}
				$tempmedia[]=$temp;
			}
		}
		$view["media"]["media"] = $tempmedia;
		if(!empty($tempmedia)){
			foreach($tempmedia as $k=>$v){
				if($tempmedia[$k]["type"]=='img'){
					$view["inum"]+=1;
				}elseif($tempmedia[$k]["type"]=='voice'){
					$view["vnum"]+=1;
				}elseif($tempmedia[$k]["type"]=='video'){
					$view["dnum"]+=1;
				}elseif($tempmedia[$k]["type"]=='news'){
					$view["nnum"]+=1;
				}
			}
		}
		$keylist = $this->arrdata("*","wxrequest_info","where id IN({$view['tkey']})");
		if(!empty($keylist)){
			foreach($keylist as $k=>$v){
				$view["keylist"][$k]["tkey"]=$keylist[$k]["tkey"];
				$view["keylist"][$k]["mode"]=$keylist[$k]["mode"];
			}
		}
		$data["error"]=1000;
		$data["msg"]=$view;
		echo json_encode($data);
		exit;
	}
	
	//群发管理
	public function sendwxmsg(){
		if(empty($this->userinfo)){Lxbase::gologin();}
		if(!empty($_POST)){
			$type=intval($_POST["type"]);
			$sendtype=intval($_POST["sendtype"]);
			if($sendtype==2){
				$sel = intval($_POST["groupid"]);	
			}elseif($sendtype==3){
				if(!empty($_POST["fenlist"])){
					$sel = trim(explode(",",$_POST["fenlist"]));
				}else{
					die(jsfshow('请填写想发送的粉丝'));
				}
			}else{
				$sel='';
			}
			if($type==1){
				$content=$_POST["content"];
				if(empty($content)){die(jsfshow('请填写要发送的文字'));}
			}else{
				$content=$_POST["media_id{$type}"];
				if(empty($content)){die(jsfshow('请选择或上传要发送的素材'));}
			}
			$modearr = array(1=>"text",2=>"image",3=>"voice",4=>"mpvideo",5=>"mpnews");
			if($type==4){
				$tit=$_POST["tit"];
				$desc=$_POST["desc"];
				$data["media_id"] = $content;
			}elseif($type==5){
				$data=$content;
			}else{
				$data=$content;
			}
			if($this->wxsendall($sel='',$modearr[$type],$content)){
				$this->setdata("wxsend","content='{$content}',type={$type},send='{$sel}',tim=now(),status=1,userid={$this->userinfo['userid']}");
				echo "<script>alert('发送成功');parent.location.href='?g=wx&m=weixin&a=sendlist'</script>";
			}else{
				$this->setdata("wxsend","content='{$content}',type={$type},send='{$sel}',tim=now(),status=0,userid={$this->userinfo['userid']}");
				echo "<script>alert('发送失败');parent.location.href='?g=wx&m=weixin&a=sendlist'</script>";
			}
			exit;
		}else{
			$iswxputdone = $this->viewdata("id","wxuser","where userid={$this->userinfo['userid']}");
			if(empty($iswxputdone)){die("<script>location.href='".$this->basehost."index.php?g=user&m=member&a=company&selnum=wx'</script>");}
			$wxgroup = $this->getwxgroup();
			$this->smarty->assign("wxgroup",$wxgroup);
			$this->smarty->display("wx_msg.tpl");
		}
	}
	
	//微信群发
	public function sendlist(){
		if(empty($this->userinfo)){Lxbase::gologin();}
		$iswxputdone = $this->viewdata("id","wxuser","where userid={$this->userinfo['userid']}");
		if(empty($iswxputdone)){die("<script>location.href='".$this->basehost."index.php?g=user&m=member&a=company&selnum=wx'</script>");}
		if($_GET["action"]=='del'){
			$id=intval($_GET["id"]);
			if(empty($id)){die(jsfshow('参数错误'));}
			$this->deldata("wxsend","where userid={$this->userinfo['userid']} and id={$id}"); 
			header("location:?g=wx&m=weixin&a=sendlist");
			exit;
		}
		$list = $this->arrdata("*","wxsend","where userid={$this->userinfo['userid']}");
		if(!empty($list)){
			foreach($list as $k=>$v){
				$list[$k]["statusname"]=empty($list[$k]["status"])?'发送失败':'发送成功';
				if($list[$k]["type"]>1){
						$url = $this->oncedata("url","wxmedia","where media_id='".$list[$k]["content"]."'");
					if($list[$k]["type"]==2){
						$list[$k]["content"]='<img src="'.$url.'" style="max-width:80px;max-height:80px" />';
					}elseif($list[$k]["type"]==3){
						$list[$k]["content"]='<audio controls="controls" src="'.$url.'">您的浏览器不支持H5音频播放</audio>';
					}elseif($list[$k]["type"]==4){
						$list[$k]["content"]='<video controls="controls" width="80" src="'.$url.'">您的浏览器不支持H5音频播放</video>';
					}elseif($list[$k]["type"]==5){
						$list[$k]["content"]='多条图文';
					}
				}
			}
			$this->smarty->assign("list",$list);
		}
		$this->smarty->display("wx_sendlist.tpl");
	}
	
	//素材库管理
	public function wxmedia(){
		if(empty($this->userinfo)){Lxbase::gologin();}
		$iswxputdone = $this->viewdata("id","wxuser","where userid={$this->userinfo['userid']}");
		if(empty($iswxputdone)){die("<script>location.href='".$this->basehost."index.php?g=user&m=member&a=company&selnum=wx'</script>");}
		$type=empty($_GET["type"])?"news":$_GET["type"];
		$mode = $type=='image'?'img':$type;
		$list = $this->arrdata("*","wxmedia","where type='{$mode}' and userid={$this->userinfo['userid']}");
		if($type=='news' && !empty($list)){
			foreach($list as $k=>$v){
				$tempdata = unserialize(base64_decode($list[$k]["content"]));
				$list[$k]["first"] = array_shift($tempdata["articles"]);
				if(!empty($list[$k]["first"]["thumb_media_id"])){
					$list[$k]["first"]["url"] = $this->oncedata("url","wxmedia","where media_id='".$list[$k]["first"]["thumb_media_id"]."'");
				}
				$more = $tempdata["articles"];
				if(!empty($more)){
					foreach($more as $kk=>$vv){
						if(!empty($more[$kk]["thumb_media_id"])){
						$more[$kk]["url"] = $this->oncedata("url","wxmedia","where media_id='".$more[$kk]["thumb_media_id"]."'");
						}
					}
				}
				$list[$k]["more"] = $more;
			}
		}
		$this->smarty->assign("list",$list);
		$this->smarty->assign("type",$type);
		$this->smarty->display("wx_media.tpl");
	}
	
	//JAJX获得素材库列表
	public function getmedialist(){
		if(empty($this->userinfo)){die(json_encode(array("error"=>1009,"msg"=>"登陆状态已失效，请重新登陆")));}
		$type=empty($_GET["type"])?"news":$_GET["type"];
		$list = $this->arrdata("*","wxmedia","where userid={$this->userinfo['userid']} and type='{$type}'");
		if($type=='news' && !empty($list)){
			foreach($list as $k=>$v){
				$tempdata = unserialize(base64_decode($list[$k]["content"]));
				$list[$k]["first"] = array_shift($tempdata["articles"]);
				$list[$k]["ntitle"] = $list[$k]["first"]["title"];
				if(!empty($list[$k]["first"]["thumb_media_id"])){
					$list[$k]["url"] = $this->oncedata("url","wxmedia","where media_id='".$list[$k]["first"]["thumb_media_id"]."'");
				}
			}
		}
		echo json_encode($list);
		exit;
	}
	
	//获得某个资源的详细信息
	public function getmediabyid(){
		if(empty($this->userinfo)){die(json_encode(array("error"=>1009,"msg"=>"登陆状态已失效，请重新登陆")));}
		$media_id=$_GET["media_id"];
		$view = $this->viewdata("*","wxmedia","where media_id='{$media_id}'");
		if(empty($view)){
			die(json_encode(array("error"=>1001,"msg"=>"资源不存在")));
		}
		if($view["type"]=='news'){
			$temp = unserialize(base64_decode($view["content"]));
			if(!empty($temp["articles"])){
				$view["content"] = array_shift($temp["articles"]);
				$view["url"] = $this->oncedata("url","wxmedia","where media_id='".$view["content"]["thumb_media_id"]."'");
			}
		}
		echo json_encode(array("error"=>1000,"data"=>$view));
		exit;
	}
	
	//素材管理上传接口
	public function mediaupload(){
		if(empty($this->userinfo)){Lxbase::gologin();}
		$type=$_POST["type"];
		if(empty($type) || !in_array($type,array('image','voice','video'))){
			die(jsfshow('素材类型错误'));
		}
		if(empty($_FILES[$type]["size"])){
			die(jsfshow('上传文件错误，请重新选择上传文件'));
		}
		$tempurl = $this->settempfile($_FILES[$type]);
		if($type=='voice'){
			$title=$_POST["title"];
			$into="type='voice',title='{$title}',content='素材库上传语音'"; 
			$ret = $this->setmedia($tempurl,$type);
		}elseif($type=='video'){
			$title=$_POST["title"];
			$desc=$_POST["desc"];
			$data["file"]=$tempurl;
			$data["title"]=$title;
			$data["desc"]=$desc;
			$temurl=$data;
			$into="type='video',title='{$title}',content='{$desc}'";
			$ret = $this->setmedia($data,$type);
		}else{
			$into="type='img',title='素材库上传图片',content='素材库上传图片'";
			$ret = $this->setmedia($tempurl,$type);
		}
		if(!empty($ret) && is_array($ret)){
			die('<script>parent.loadhide("上传素材失败-'.$ret["errmsg"].'")</script>');
		}else{
			$media_id=$ret;
			//同步微信素材
			$picdata = $this->upload($_FILES[$type],'wxmedia');
			if(empty($picdata)){
				die('<script>parent.loadhide("同步素材失败，请重试")</script>');
			}
			$picurl=$picdata["pic"];
			//资源入库
			$this->setdata("wxmedia","userid={$this->userinfo['userid']},media_id='{$media_id}',".$into.",url='{$picurl}',tim=now()");
		}
		echo "<script>alert('添加资源成功');parent.location.href='?g=wx&m=weixin&a=wxmedia&type=".$type."'</script>";
		exit;
	}
	
	//保存微信用户信息
	public function wxusersave(){
		if(empty($this->userinfo)){Lxbase::gologin();}
		$wxtitle=$_POST["wxtitle"];
		$wxname=$_POST["wxname"];
		$appid=$_POST["appid"];
		$secret=$_POST["secret"];
		$token=$_POST["token"];
		$shopid=$_POST["shopid"];
		$shopkey=$_POST["shopkey"];
		$aeske=$_POST["aeske"];
		$rcode=$_POST["rcode"];
		$wxtype=intval($_POST["wxtype"]);
		$into="wxtitle='{$wxtitle}',wxname='{$wxname}',appid='{$appid}',secret='{$secret}',rcode='{$rcode}',token='{$token}',shopid='{$shopid}',shopkey='{$shopkey}',aeske='{$aeske}',wxtype={$wxtype},userid={$this->userinfo['userid']}";
		$ishave = $this->viewdata("id","wxuser","where userid={$this->userinfo['userid']}");
		if(empty($ishave)){
			$into.=",acctoken='',acctokentim=0,ticket='',tickettim=0";
			$this->setdata("wxuser",$into);
		}else{
			$this->updata("wxuser",$into,"where id={$ishave['id']}");
		}
		$vqdb = Lxbase::getconfig("olddb");
		$vqconn = new Lxbase($vqdb);
		$oldinfo = $vqconn->viewdata("id,token","wxuser","where appid='{$appid}'");
		$oldtoken = $_SESSION["userinfo"]['token'];
		$olduid = $vqconn->oncedata("id","users","where token='{$oldtoken}'");
		if(empty($oldinfo)){
			$into="routerid='',agentid=0,uid={$olduid},wxname='{$wxtitle}',winxintype={$wxtype},aeskey='{$aeskey}',encode=0,appid='{$appid}',appsecret='{$secret}'";
			$into.=",wxid='',weixin='{$wxname}',headerpic='".$pic["pic"]."',token='{$oldtoken}',pigsecret='',province='',city='',qq='',wxfans=0,typeid=8,typename='',tongji='',allcardnum=0,cardisok=0";
			$into.=",yetcardnum=0,totalcardnum=0,createtime=".time().",tpltypeid=1,updatetime=".time().",tpltypename='ty_index',tpllistid=1,tpllistname='yl_list',tplcontentid=1";
			$into.=",tplcontentname='ktv_content',transfer_customer_service=0,openphotoprint=0,freephotocount=3,oauth=1,oauthinfo=1,color_id=0,ifbiz=0";
			$into.=",fuwuappid=0,share_ticket='',share_dated='',authorizer_access_token='',authorizer_refresh_token='',authorizer_expires='',type=0,web_access_token=''";
			$into.=",web_refresh_token='',web_expires='',wx_coupons=0,card_ticket='',card_expires='',wx_liaotian=0,qr='".$pic["pic"]."',dynamicTmpls=0";
			$into.=",sub_notice='您好，您还没有权限参加活动',need_phone_notice='您好，需要您先填写个人信息才能参加活动',sub_notice_btn='立即获得权限'";
			$vqconn->setdata("wxuser",$into);
		}else{
			$into="wxname='{$wxtitle}',token='{$oldtoken}',winxintype={$wxtype},aeskey='{$aeskey}',appid='{$appid}',appsecret='{$secret}',weixin='{$wxname}'";
			$vqconn->updata("wxuser",$into,"where id={$oldinfo['id']}");
		}
		die(jsfshow('微信资料更新成功'));
	}
	
	//保存并发布微信菜单
	public function menusave(){
		if(empty($this->userinfo)){Lxbase::gologin();}
		$m=1;
		for($i=1;$i<100;$i++){
			$btitle = 'title'.$i;
			$stitle = 'stitle'.$i;
			$btype = 'type'.$i;
			$stype = 'stype'.$i;
			$bcon = 'con'.$i;
			$scon = 'scon'.$i;
			$$btitle = $_POST[$btitle];
			$$stitle = $_POST[$stitle];
			$$btype = $_POST[$btype];
			$$stype = $_POST[$stype];
			$$bcon = $_POST[$bcon];
			$$scon = $_POST[$scon];
			$sdata=array();
			$j=0;
			if(!empty($$stype) || !empty($$scon)){
				$maxnum=count($$stype) - 1;
				ksort($$stype);
				ksort($$scon);
				ksort($$stitle);
				foreach($$stype as $k=>$v){
					$temp_type = $$stype;
					$temp_title = $$stitle;
					$temp_con = $$scon;
					$sdata[$maxnum-$j]["type"] = $temp_type[$k];
					$sdata[$maxnum-$j]["name"] = $temp_title[$k];
					if($temp_type[$k]=='click'){
						$sdata[$maxnum-$j]["key"]=$temp_con[$k];
					}elseif($temp_type[$k]=='view'){
						$sdata[$maxnum-$j]["url"]=$temp_con[$k];
					}elseif($temp_type[$k]=='media_id'){
						$sdata[$maxnum-$j]["media_id"]=$temp_con[$k];
					}
					$savedata["stitle"][$i][$j] = $temp_title[$k];
					$savedata["stype"][$i][$j] = $temp_type[$k];
					$savedata["scon"][$i][$j] = $temp_con[$k];
					krsort($savedata["stitle"][$i]);
					krsort($savedata["stype"][$i]);
					krsort($savedata["scon"][$i]);
					$j++;
				}
				ksort($sdata);
				$data[] = array("name"=>$$btitle,"sub_button"=>$sdata);
				$savedata["btitle"][$m]=$$btitle;
				$m++;
			}elseif(!empty($$btitle)){
				$bdata["type"]=$$btype;
				$bdata["name"]=$$btitle;
				$savedata["btitle"][$m]=$$btitle;
				$savedata["btype"][$m]=$$btype;
				$savedata["bcon"][$m]=$$bcon;
				if($$btype=='click'){
					$bdata["key"]=$$bcon;
				}elseif($$btype=='view'){
					$bdata["url"]=$$bcon;
				}elseif($$btype=='media_id'){
					$bdata["media_id"]=$$bcon;
				}
				$data[] = $bdata;
				$m++;
			}else{
				continue;
			}
		}
		$n=1;
		$ret = $this->menu_create($data);
		if(is_array($ret)){
			die(jsfshow('创建菜单失败-'.$ret["errmsg"]));
		}elseif($ret==1){
			$btitle=serialize($savedata["btitle"]);
			$btype=serialize($savedata["btype"]);
			$bcon=serialize($savedata["bcon"]);
			$stitle=serialize($savedata["stitle"]);
			$stype=serialize($savedata["stype"]);
			$scon=serialize($savedata["scon"]);
			$into="btitle='{$btitle}',btype='{$btype}',bcon='{$bcon}',stitle='{$stitle}',stype='{$stype}',scon='{$scon}'";
			$ishave = $this->viewdata("id","wxmenu","where userid={$this->userinfo['userid']}");
			if(empty($ishave)){
				$into.=",userid={$this->userinfo['userid']}";
				$this->setdata("wxmenu",$into);
			}else{
				$this->updata("wxmenu",$into,"where userid={$this->userinfo['userid']}");
			}
			die(jsfshow('创建菜单成功,新菜单24小时内生效'));
		}else{
			die(jsfshow('创建菜单失败'));
		}
		exit;
	}
	
	//上传新闻图片
	public function upnewspic(){
		if(empty($this->userinfo)){die(json_encode(array("error"=>1009,"msg"=>"登陆状态已失效，请重新登陆")));}
		$imgname=$_GET["imgname"];
		if(empty($_FILES[$imgname]["size"])){
			die(json_encode(array('error'=>1001,"msg"=>"请上传正确的图片文件")));
		}
		$srcInfo = getimagesize($_FILES[$imgname]["tmp_name"]);
		if(!in_array($srcInfo[2],array(1,2,3,6))){
			die(json_encode(array('error'=>1002,"msg"=>"上传格式只支持jpg,gif,png,请选择正确的格式上传")));
		}
		$tempurl = $this->settempfile($_FILES[$imgname]);
		$ret = $this->setmedia($tempurl,"image");
		if(is_array($ret)){
			echo json_encode(array("error"=>1005,"msg"=>"上传素材失败-".$ret["errmsg"]));
			exit;
		}else{
			$media_id=$ret;
			//同步微信素材
			$picdata = $this->upload($_FILES[$imgname],'wxrequest');
			if(empty($picdata)){
				echo json_encode(array("error"=>1003,"msg"=>"同步素材失败，请重试"));
				exit;
			}
			$picurl=$picdata["pic"];
			//资源入库
			$newid = $this->setdata("wxmedia","userid={$this->userinfo['userid']},media_id='{$media_id}',type='img',title='图文素材图片',content='图文素材图片',url='{$picurl}',tim=now()");
		}
		echo json_encode(array('error'=>1000,"msg"=>"上传成功","pic"=>$picdata["pic"],"media_id"=>$media_id));
		exit;
	}
	
	//HTML内部图片转换成微信图片地址
	public function putwximgsrc($content){
		$content=stripslashes($content);
		$pattern="/<img.*?src=[\'|\"](.*?(?:[\.gif|\.jpg|\.png|\.jpeg]))[\'|\"].*?[\/]?>/i";
		preg_match_all($pattern,$content,$match);
		$srcarr = $match[1];
		foreach($srcarr as $k=>$v){
			$hz = array_pop(explode(".",$v));
			$tempurl = $this->settempfile(file_get_contents($v),$hz);
			$rinfo = $this->getmediaurl($tempurl);
			if(!empty($rinfo) && !is_array($rinfo)){
				$content = str_replace($v,$rinfo,$content);
			}
		}
		return $content;
	}
	
	public function fenlist(){
		$nick=$_POST['nick_name'];
		$bs_id=$this->userinfo['userid'];
		$group=$this->getwxgroup();
		//var_dump($group);exit;
		if(!($group) || !is_array($group)){
			foreach($group as $k=>$v){
				if(empty($group[$k]["id"])){
					$group[$k]["name"]="默认组";
				}
			}
		}
		$page=empty($_GET["page"])?1:intval($_GET["page"]);
		$pagesize=20;
		$pagenum = ($page - 1) * $pagesize;
		$where="where userid={$this->userinfo['userid']}";
		if(isset($nick) && !empty($nick)){
			$where .=" and uname like '%{$nick}%'";
		}
		$list = $this->arrdata("*","wxguest",$where,"id desc","limit {$pagenum},{$pagesize}");
		$sort[]="g=".$_GET["g"];
		$sort[]="m=".$_GET["m"];
		$sort[]="a=".$_GET["a"];
		$pagestr = $this->termpage("wxguest",$where,$sort,$page,$pagesize);
		$this->smarty->assign("list",$list);
		$this->smarty->assign("pagestr",$pagestr);
		$this->smarty->assign("group",$group);
		$this->smarty->display("fenlist.tpl");
	}

	//新建分组
	public function fans_group()
	{
			//获取商家的id
			$bs_id=$_SESSION['userinfo']['userid'];
			$user_data=$this->viewdata("*","wxuser","where userid=$bs_id");
			if(time()>$user_data['acctokentim']){
				$this->setwxinfo($bs_id);
				$user_token=$this->acctoken;
			}else{
				$user_token=$user_data['acctoken'];
			}
			$group_name=$_POST['group_name'];
			$url = "https://api.weixin.qq.com/cgi-bin/groups/create?access_token=$user_token";
			$data = array("group" => array("name"=>$group_name));
			$data = json_encode($data,JSON_UNESCAPED_UNICODE);
			$res = json_decode($this->call_post($url,$data),true);
            die("<script>alert('分组添加成功');parent.location.href='?g=wx&m=weixin&a=fenlist'</script>");
	}

	//修改备注信息
	public function updata_nick(){

		$fen=new Wx();
		$remark_name=$_POST['uname'];
		$id=intval($_POST["id"]);
		$openid = $this->oncedata("openid","wxguest","where id={$id}");
		//获取商家的id，再获取商家的token
		$bs_id=$this->userinfo['userid'];
		$user_data=$this->viewdata("*","wxuser","where userid={$bs_id}");
		if(time()>$user_data['acctokentim']){
			$fen->setwxinfo($bs_id);
			$user_token=$fen->acctoken;

		}else{
			$user_token=$user_data['acctoken'];
		}
		$url="https://api.weixin.qq.com/cgi-bin/user/info/updateremark?access_token=$user_token";
		$data=json_encode(array("openid"=>$openid,"remark"=>$remark_name));
		$res = json_decode($this->call_post($url, $data),true);
		//成功之后修改本地数据表的数据
		$this->updata("wxguest","remark='{$remark_name}'","where openid='{$openid}' and userid='{$bs_id}'");
		die("<script>alert('修改备注成功');parent.saveremark('".$remark_name."',{$id});</script>");
	}

	//更新当前用户粉丝信息
	public function updateguest(){
		$userid=$this->userinfo["userid"];
		$ret = $this->getfanslist($userid);

		if(empty($ret["data"]["openid"])){
			echo "<script>parent.fansup()</script>";
		}else{
			$openids = $ret["data"]["openid"];
			$sexarr = array(0=>'未知',1=>'男',2=>'女');
			foreach($openids as $k=>$v){
				$info = $this->getfansinfo($this->acctoken,$v);
				if(!empty($info["openid"])){
					$ishave = $this->viewdata("id","wxguest","where openid='{$v}'");
					$uname=(isset($info["nickname"]) && !empty($info["nickname"])) ? addslashes($info["nickname"]) : '';
					$uname = preg_replace('/[\x{10000}-\x{10FFFF}]/u', '', $uname);
					$remark = (isset($info["remark"]) && !empty($info["remark"]))?addslashes($info["remark"]):$uname;
					$remark = preg_replace('/[\x{10000}-\x{10FFFF}]/u', '', $remark);
					$uid=$this->userinfo["token"];
					$openid = $v;
					$uface=$info["headimgurl"];
					$sex_code = $info['sex'];
					$sex = $sexarr[$sex_code];
					$province=$info["province"];
					$province = preg_replace('/[\x{10000}-\x{10FFFF}]/u', '', $province);
					$city=$info["city"];
					$city = preg_replace('/[\x{10000}-\x{10FFFF}]/u', '', $city);
					$subscribe_time = $info["subscribe_time"];
					$userid=$this->userinfo["userid"];
					$tim=time()+(7*86400);
					$groupid=$info["groupid"];
					$into="uname='{$uname}',remark='{$remark}',uface='{$uface}',sex='{$sex}',province='{$province}',city='{$city}',subscribe_time={$subscribe_time},groupid={$groupid}";
					if(!empty($ishave)){
						$this->updata("wxguest",$into,"where id={$ishave['id']}");
					}else{
						$into.=",uid='{$uid}',openid='{$openid}',token='',rtoken='',tokentim=0,userid={$userid},tim={$tim}";
						$this->setdata("wxguest",$into);
					}
				}else{
					continue;
				}
			}
			echo "<script>parent.fansup();</script>";
			exit;
		}
	}

	//获取粉丝的详细信息
	public function get_fans_info(){
		//当前粉丝的id
		$fans_id=$_GET['id'];
		//当前粉丝的所有信息
		$fans_info=$this->viewdata("*","wxguest","where id=$fans_id");
		$this->smarty->assign("fans_info",$fans_info);
		$this->smarty->display("updata_nick.tpl");
	}

	//修改粉丝的组别
	public function updata_group(){

	//要取的被修改的组别的粉丝的信息
		$openid=$_POST['openid'];
		$groupid=$_POST['groupid'];
		$bs_id=$this->userinfo['userid'];
		$user_data=$this->viewdata("*","wxuser","where userid=$bs_id");
		if(time()>$user_data['acctokentim']){
			$this->setwxinfo($bs_id);
			$user_token=$this->acctoken;
		}else{
			$user_token=$user_data['acctoken'];
		}
		//移动用户分组
		$url="https://api.weixin.qq.com/cgi-bin/groups/members/update?access_token=$user_token";
		$data=array("openid"=>$openid,"to_groupid"=>$groupid);
		$data=json_encode($data);
		$res=json_decode($this->call_post($url,$data),true);
		$this->updata("wxguest","groupid={$groupid}","where openid='{$openid}' and userid={$bs_id}");
		echo json_encode(array("msg"=>"true"));
		exit;
}

	//删除分组
	public function del_group(){
		$groupids=$_POST['groupid'];
		$bs_id=$this->userinfo['userid'];
		$user_data=$this->viewdata("*","wxuser","where userid=$bs_id");
		if(time()>$user_data['acctokentim']){
			$this->setwxinfo($bs_id);
			$user_token=$this->acctoken;
		}else{
			$user_token=$user_data['acctoken'];
		}
		foreach($groupids as $key=>$value){
			$url="https://api.weixin.qq.com/cgi-bin/groups/delete?access_token=$user_token";
			$data=array("group"=>array("id"=>$value));
			$data=json_encode($data);
			$res=json_decode($this->call_post($url,$data),true);
			$this->updata("wxguest","groupid=0","where groupid=$value and userid=$bs_id");
		}
	}

	//根据用户的昵称查询
	public function get_by_nick(){
		//var_dump($_POST);exit;
		$nick=$_GET['nick_name'];
		$bs_id=$this->userinfo['userid'];
		//var_dump("select * from wxguest where uname='{$nick}' and userid={$bs_id}");exit;
		$list=$this->viewdata("*","wxguest","where uname='{$nick}' and userid={$bs_id}");
		$this->smarty->assign("list",$list);
		$this->smarty->display("fenlist.tpl");
	}
	//添加微信图文信息
	public function wxnews(){
		if(empty($this->userinfo)){Lxbase::gologin();}
		if(!empty($_POST)){
			for($i=1;$i<9;$i++){
				$title='title'.$i;
				$author='author'.$i;
				$content='content'.$i;
				$linkurl='linkurl'.$i;
				$desc='desc'.$i;
				$media_id='media_id'.$i;
				$title=$_POST[$title];
				$author=$_POST[$author];
				$content=str_replace("%nbsp","&nbsp",str_replace('\r\n','',$_POST[$content]));
				$content=str_replace("<p><br/>","",str_replace("	","",$content));
				$linkurl = $_POST[$linkurl];
				$desc=strip_tags(str_replace('\r\n','',$_POST[$desc]));
				$media_id = $_POST[$media_id];
				if(!empty($title) && empty($media_id)){
					die(jsfshow('请上传或选择第'.$i.'条图文的封面图片'));
				}
				if(!empty($media_id) && empty($title)){
					die(jsfshow('请填写第'.$i.'条图文的标题'));
				}
				if(!empty($title) && !empty($media_id)){
					$data["title"] = $title;
					$data["thumb_media_id"] = $media_id;
					$data["author"] = $author;
					$data["digest"]=$desc;
					$data["show_cover_pic"]=1;
					$data["content"]=$this->putwximgsrc($content);
					$data["content_source_url"]=$linkurl;
					$savedata["title"] = $title;
					$savedata["thumb_media_id"] = $media_id;
					$savedata["author"] = $author;
					$savedata["digest"]=$desc;
					$savedata["show_cover_pic"]=1;
					$savedata["content"]=$content;
					$savedata["content_source_url"]=$linkurl;
					$wxdata["articles"][]=$data;
					$svdata["articles"][]=$savedata;
				}else{
					continue;
				}
			}
			$id=intval($_POST["id"]);
			if(empty($id)){
				$content = base64_encode(serialize($svdata));
				$ishave = $this->viewdata("*","wxmedia","where content='{$content}'");
				if(!empty($ishave)){
					die(jsfshow('您已添加过一样的图文消息，请在素材管理中查看'));
				}
				$ret = $this->setmedia($wxdata);
				if(is_array($ret)){
					die(jsfshow($ret["errmsg"]));
				} 
				$into="userid={$this->userinfo['userid']},media_id='{$ret}',type='news',title='图文素材',content='{$content}',url='',tim=now()";
				$this->setdata("wxmedia",$into);
				echo "<script>alert('图文素材添加成功，您可以在选择图文素材中选用该素材')</script>";
			}else{
				$view = $this->viewdata("*","wxmedia","where id={$id}");
				if(empty($view["media_id"])){die(jsfshow('素材ID错误'));}
				if($this->userinfo["userid"] != $view["userid"]){
					die(jsfshow('用户权限错误'));
				}
				$templist = $wxdata["articles"];
				foreach($templist as $k=>$v){
					$tempdata["media_id"]=$view["media_id"];
					$tempdata["index"]=$k;
					$tempdata["articles"]["title"] = $templist[$k]["title"];
					$tempdata["articles"]["thumb_media_id"] = $templist[$k]["thumb_media_id"];
					$tempdata["articles"]["author"] = $templist[$k]["author"];
					$tempdata["articles"]["digest"] = $templist[$k]["digest"];
					$tempdata["articles"]["show_cover_pic"] = 1;
					$tempdata["articles"]["content"] = $templist[$k]["content"];
					$tempdata["articles"]["content_source_url"] = $templist[$k]["content_source_url"];
					$this->updatenews($tempdata);
				}
				$content = base64_encode(serialize($svdata));
				$this->updata("wxmedia","content='{$content}'","where id={$id}");
				echo "<script>alert('图文素材修改成功，您可以在选择图文素材中选用该素材');window.close()</script>";
			}
			exit;
		}else{
			$maxeditid=1;
			if(!empty($_GET["id"])){
				$id=intval($_GET["id"]);
				$view = $this->viewdata("*","wxmedia","where id={$id}");
				$this->smarty->assign("view",$view);
				if(!empty($view)){
					$templist = unserialize(base64_decode($view["content"]));
					if(!empty($templist["articles"])){
						$list = $templist["articles"];
						foreach($list as $k=>$v){
							$list[$k]["url"] = $this->oncedata("url","wxmedia","where media_id='".$list[$k]["thumb_media_id"]."'");
							$list[$k]["content"] = str_replace("<br />",'',stripslashes($list[$k]["content"]));
						}
						$maxeditid=count($list);
						$this->smarty->assign("list",$list);
					}
				}
			}
			if($this->basehost=='http://kaifa.zq.zhongsou.com/' || $this->basehost=='http://zq.zhongsou.com/'){
				$vqhost = "http://kaifa.vq.zhongsou.com/";
			}else{
				$vqhost = "http://vq.zhongsou.com/";
			}
			$usertoken = $this->oncedata("token","users","where id={$this->userinfo['userid']}");
			$this->smarty->assign("basehost",$this->basehost);
			$this->smarty->assign("maxeditid",$maxeditid);
			$this->smarty->assign("usertoken",$usertoken);
			$this->smarty->assign("vqhost",$vqhost);
			$this->smarty->display("wx_news.tpl");
		}
	}
	//批量的移动组别信息
	public function mvoe_num(){
		$openids=$_POST['listids'];
		$to_groupid=$_POST['groupid'];
		$bs_id=$this->userinfo['userid'];
		$user_data=$this->viewdata("*","wxuser","where userid=$bs_id");
		if(time()>$user_data['acctokentim']){
			$this->setwxinfo($bs_id);
			$user_token=$this->acctoken;
		}else{
			$user_token=$user_data['acctoken'];
		}
		$url="https://api.weixin.qq.com/cgi-bin/groups/members/batchupdate?access_token=$user_token";
		$data=array("openid_list"=>$openids,"to_groupid"=>$to_groupid);
		$data=json_encode($data);
		$res=json_decode($this->call_post($url,$data),true);
		//var_dump("updata from wxguest set groupid={$to_groupid} where openid in '{$openids}' and userid={$bs_id}");exit;
		foreach($openids as $k=>$v){
			$this->updata("wxguest","groupid={$to_groupid}","where openid='{$v}' and userid={$bs_id}");
		}
		echo json_encode(array("msg"=>"true"));
		exit;
	}

	
	public function getfansnum(){
		$ulist = $this->arrdata("*","wxuser","where appid<>'' and secret<>'' and acctoken<>''");
		$total=0;
		foreach($ulist as $k=>$v){
			$ret = $this->getfanslist($v["userid"]);
			if(!empty($ret["total"])){
				$total = $total + intval($ret["total"]);
			}
		}
		echo $total;
		exit;
	}

	//添加客服账号
	public function add_kf(){

		if($_POST){
			$bs_id=$this->userinfo['userid'];
			//$bs_id=14;
			$img=$_FILES['img_url'];
			$em_id=$_POST['em_id'];
			$nick=$_POST['nick'];
			$password=md5($_POST['password']);
			$res_img=$this->upload($img,'kefu');
			$user_data=$this->arrdata("*","wxkefu","where bs_id={$bs_id}");
			//获取账号的微信号
			$wxname=$this->viewdata("wxname","wxuser","where userid={$bs_id}");
			//$reg="/^[x{4e00}-x{9fa5}a-za-z0-9_]+$/u";
			//var_dump(preg_match($reg,$wxname['wxname']));exit;
			$emploey_id=$em_id.'@'.$wxname['wxname'];


			//var_dump($emploey_id);exit;
			if(time()>$user_data['acctokentim']){
				$this->setwxinfo($bs_id);
				$user_token=$this->acctoken;
			}else{
				$user_token=$user_data['acctoken'];
			}

			$url="https://api.weixin.qq.com/customservice/kfaccount/add?access_token=$user_token";
			$data=array(
					"kf_account"=>$emploey_id,
					"nickname"=>$nick,
					"password"=>$password,
			);
			$data=json_encode($data,JSON_UNESCAPED_UNICODE);
			//var_dump($data);
			$res=json_decode($this->call_post($url,$data),true);
			//var_dump($res);exit;
			foreach($user_data as $k=>$v){
				if($emploey_id==$v['em_id']){
					//echo "此工号已经创建";exit;
					return;
				}
			}
			$info=array(
					'bs_id'=>$bs_id,
					'img_url'=>$res_img['pic'],
					'nick'=>$nick,
					'em_id'=>$emploey_id,
					'password'=>$password,
			);
			$this->setdata("wxkefu",$info);
			header("location:?g=wx&m=weixin&a=show_kf");


		}else{
			$bs_id=$this->userinfo['userid'];
			$wxname=$this->viewdata("wxname","wxuser","where userid=$bs_id");
			$this->smarty->assign("wxname",$wxname);
			$this->smarty->display("wx_add_kefu.tpl");
		}

	}
	//展示客服列表
	public function show_kf(){
		$bs_id=$this->userinfo['userid'];
		$data_kefu=$this->arrdata("*","wxkefu","where bs_id={$bs_id}");
		$this->smarty->assign("data_kefu",$data_kefu);
		$this->smarty->display("wx_show_kefu.tpl");
	}

	//删除客服记录
	public function del_kf(){
		$bs_id=$this->userinfo['userid'];
		$id=$_GET['id'];
		$user_data=$this->viewdata("*","wxkefu","where bs_id=$bs_id");
		$em_id=$user_data['em_id'];
		if(time()>$user_data['acctokentim']){
			$this->setwxinfo($bs_id);
			$user_token=$this->acctoken;
		}else{
			$user_token=$user_data['acctoken'];
		}
		$url="https://api.weixin.qq.com/customservice/kfaccount/del?access_token=$user_token&kf_account=$em_id";
		$this->call_get($url);
		$this->deldata("wxkefu","where id={$id} and bs_id={$bs_id}");
		header("location:?&g=wx&m=weixin&a=show_kf");
	}

	//修改客服账号信息
	public function update_kf()
	{
		if(isset($_POST['nick'])){
			//var_dump($_FILES);
			//var_dump($_POST);exit;
			$bs_id=$this->userinfo['userid'];
			$id=$_POST['id'];
			$em_id=$_POST['em_id'];
			$nick=$_POST['nick'];
			$password=$_POST['password'];


			//var_dump($pic);exit;
			//说明是更新的操作
			$user_data=$this->viewdata("*","wxkefu","where bs_id=$bs_id");
			if(time()>$user_data['acctokentim']){
				$this->setwxinfo($bs_id);
				$user_token=$this->acctoken;
			}else{
				$user_token=$user_data['acctoken'];
			}
			$url="https://api.weixin.qq.com/customservice/kfaccount/update?access_token=$user_token";
			$data=array(
					    "kf_account" =>$em_id,
						"nickname" => $nick,
						"password" =>$password,
			);
			$data=json_encode($data);
			$this->call_post($url,$data);
			if(!empty($_FILES['img_url']['size'])){
				$img=$_FILES['img_url'];
				$res=$this->upload($img,'kefu');
				$pic=$res['pic'];
				$info="img_url='{$pic}',em_id='{$em_id}',nick='{$nick}',password='{$password}'";
				$this->updata("wxkefu",$info,"where id={$id} and bs_id={$bs_id}");
			}
			//var_dump(" update from wxkefu set img_url='{$res['pic']}',em_id='{$em_id}',nick='{$nick}',password='{$password}' where id={$id} and bs_id={$bs_id}");exit;
			$info="em_id='{$em_id}',nick='{$nick}',password='{$password}'";
			$this->updata("wxkefu",$info,"where id={$id} and bs_id={$bs_id}");
			header("location:?g=wx&m=weixin&a=show_kf");
		}else{
			$bs_id=$this->userinfo['userid'];
			$id=$_GET['id'];
			$data_kefu=$this->viewdata("*","wxkefu","where id=$id and bs_id=$bs_id");
			$this->smarty->assign('data_kefu',$data_kefu);
			$this->smarty->display("wx_detail_kefu.tpl");
		}

	}

	//检查客服工号是否添加过
	public function checkname(){
		$card=$_POST['card'];
		$bs_id=$this->userinfo['userid'];
		$data_kefu=$this->arrdata("*","wxkefu","where bs_id=$bs_id");
		$newcard=array();
		foreach($data_kefu as $k=>$v){
			$newcard[]=$v['em_id'];
		}
		if(in_array($card,$newcard)){
			echo json_encode(array("msg"=>"true"));
			exit;
		}
	}

	//创建卡券
	public function add_card(){

		$sid=$this->userinfo['userid'];  //商户id
		$user_data=$this->viewdata("*","wxuser","where userid={$sid}");
		$wxshop=new Wx();
		if(time()>$user_data['acctokentim']){
			$wxshop->setwxinfo($sid);
			$user_token=$wxshop->acctoken;
		}else{
			$user_token=$user_data['acctoken'];
		}
		$url="https://api.weixin.qq.com/card/create?access_token=$user_token";
//		$card_type=$_POST['card_type'];
//		$logo_url=$_POST['logo_url'];
//		$brand_name=$_POST['brand_name'];
//		$code_type=$_POST['code_type'];
//		$title=$_POST['title'];
//		$sub_title=$_POST['sub_title'];
//		$color=$_POST['color'];
//		$notice=$_POST['notice'];
//		$service_phone=$_POST['service_phone'];
//		$description=$_POST['description'];
//		$type=$_POST['type'];
//		$begin_timestamp=$_POST['begin_timestamp'];
//		$end_timestamp=$_POST['end_timestamp'];
//		$quantity=$_POST['quantity'];
//		$get_limit=$_POST['get_limit'];
//		$use_custom_code=$_POST['use_custom_code'];
//		$bind_openid=$_POST['bind_openid'];
//		$can_share=$_POST['can_share'];
//		$can_give_friend=$_POST['can_give_friend'];
//		$deal_detail=$_POST['deal_detail'];
//		$least_cost=$_POST['least_cost'];
//		$reduce_cost=$_POST['reduce_cost'];
//		$discount=$_POST['discount'];
//		$gift=$_POST['gift'];
//		$default_detail=$_POST['default_detail'];

		$card_type='GENERAL_COUPON';
		$logo_url='1.JPG';
		$brand_name='海底捞';
		$code_type='CODE_TYPE_TEXT';
		$title='132元双人火锅套餐';
		$sub_title='周末狂欢必备';
		$color='Color010';
		$notice='使用时向服务员出示此券';
		$service_phone='020-88888888';
		$description='不可与其他优惠同享\n如需团购券发票，请在消费时向商户提出\n店内均可使用，仅限堂食';
		$type='DATE_TYPE_FIX_TIME_RANGE';
		$begin_timestamp=1455689853;
		$end_timestamp=1485699853;
		$quantity=500000;
		$get_limit=3;
		$use_custom_code=false;
		$bind_openid=false;
		$can_share=true;
		$can_give_friend=true;
		$deal_detail='以下锅底2选1（有菌王锅、麻辣锅、大骨锅、番茄锅、清补 凉锅、酸菜鱼锅可选）：\n大锅1份 12元\n小锅2份 16元 ';
		$least_cost=10000;
		$reduce_cost=5000;
		$discount=30;
		$gift="可兑换音乐木盒一个";
		$default_detail="音乐木盒";

		//团购post
		$groupon_data=array(
				'card'=>array(
						"card_type"=>$card_type,
						"groupon"=>array(
								"base_info"=>array(
										"logo_url"=>$logo_url,
										"brand_name"=>$brand_name,
										"code_type"=>$code_type,
										"title"=>$title,
										"sub_title"=>$sub_title,
										"color"=>$color,
										"notice"=>$notice,
										"service_phone"=>$service_phone,
										"description"=>$description,
										"date_info"=>array(
												"type"=>$type,
												"begin_timestamp"=>$begin_timestamp,
												"end_timestamp"=>$end_timestamp,
										),
										"sku"=>array(
												"quantity"=>$quantity,
										),
										"get_limit"=>$get_limit,
										"use_custom_code"=>$use_custom_code,
										"bind_openid"=>$bind_openid,
										"can_share"=>$can_share,
										"can_give_friend"=>$can_give_friend,
								),
								"deal_detail"=>$deal_detail,
						),
				),
		);
		//代金券post
		$cash_data=array(
				'card'=>array(
						"card_type"=>$card_type,
						"cash"=>array(
								"base_info"=>array(
										"logo_url"=>$logo_url,
										"brand_name"=>$brand_name,
										"code_type"=>$code_type,
										"title"=>$title,
										"sub_title"=>$sub_title,
										"color"=>$color,
										"notice"=>$notice,
										"service_phone"=>$service_phone,
										"description"=>$description,
										"date_info"=>array(
												"type"=>$type,
												"begin_timestamp"=>$begin_timestamp,
												"end_timestamp"=>$end_timestamp,
										),
										"sku"=>array(
												"quantity"=>$quantity,
										),
										"get_limit"=>$get_limit,
										"use_custom_code"=>$use_custom_code,
										"bind_openid"=>$bind_openid,
										"can_share"=>$can_share,
										"can_give_friend"=>$can_give_friend,
								),
								"reduce_cost"=>$reduce_cost,
								"least_cost"=>$least_cost,
						),
				),
		);
		//折扣券post
		$discount_data=array(
				'card'=>array(
						"card_type"=>$card_type,
						"discount"=>array(
								"base_info"=>array(
										"logo_url"=>$logo_url,
										"brand_name"=>$brand_name,
										"code_type"=>$code_type,
										"title"=>$title,
										"sub_title"=>$sub_title,
										"color"=>$color,
										"notice"=>$notice,
										"service_phone"=>$service_phone,
										"description"=>$description,
										"date_info"=>array(
												"type"=>$type,
												"begin_timestamp"=>$begin_timestamp,
												"end_timestamp"=>$end_timestamp,
										),
										"sku"=>array(
												"quantity"=>$quantity,
										),
										"get_limit"=>$get_limit,
										"use_custom_code"=>$use_custom_code,
										"bind_openid"=>$bind_openid,
										"can_share"=>$can_share,
										"can_give_friend"=>$can_give_friend,
								),
								"discount"=>$discount,
						),
				),
		);
		//兑换券post
		$gift_data=array(
				'card'=>array(
						"card_type"=>$card_type,
						"gift"=>array(
								"base_info"=>array(
										"logo_url"=>$logo_url,
										"brand_name"=>$brand_name,
										"code_type"=>$code_type,
										"title"=>$title,
										"sub_title"=>$sub_title,
										"color"=>$color,
										"notice"=>$notice,
										"service_phone"=>$service_phone,
										"description"=>$description,
										"date_info"=>array(
												"type"=>$type,
												"begin_timestamp"=>$begin_timestamp,
												"end_timestamp"=>$end_timestamp,
										),
										"sku"=>array(
												"quantity"=>$quantity,
										),
										"get_limit"=>$get_limit,
										"use_custom_code"=>$use_custom_code,
										"bind_openid"=>$bind_openid,
										"can_share"=>$can_share,
										"can_give_friend"=>$can_give_friend,
								),
								"gift"=>$gift,
						),
				),
		);
		//优惠券post
		$general_coupon_data=array(
				'card'=>array(
						"card_type"=>$card_type,
						"general_coupon"=>array(
								"base_info"=>array(
										"logo_url"=>$logo_url,
										"brand_name"=>$brand_name,
										"code_type"=>$code_type,
										"title"=>$title,
										"sub_title"=>$sub_title,
										"color"=>$color,
										"notice"=>$notice,
										"service_phone"=>$service_phone,
										"description"=>$description,
										"date_info"=>array(
												"type"=>$type,
												"begin_timestamp"=>$begin_timestamp,
												"end_timestamp"=>$end_timestamp,
										),
										"sku"=>array(
												"quantity"=>$quantity,
										),
										"get_limit"=>$get_limit,
										"use_custom_code"=>$use_custom_code,
										"bind_openid"=>$bind_openid,
										"can_share"=>$can_share,
										"can_give_friend"=>$can_give_friend,
								),
								"default_detail"=>$default_detail,
						),
				),
		);
		if($card_type=='GROUPON'){
			//团购券
			$data=$groupon_data;
		}elseif($card_type=='CASH'){
			//代金券
			$data=$cash_data;
		}elseif($card_type=='DISCOUNT'){
			//折扣券
			$data=$discount_data;
		}elseif($card_type=='GIFT'){
			//兑换券
			$data=$gift_data;
		}elseif($card_type=='GENERAL_COUPON'){
			//优惠券
			$data=$general_coupon_data;
		}

		$data=json_encode($data,JSON_UNESCAPED_UNICODE);
		//var_export($data);exit;
		$res=json_decode($this->call_post($url,$data),true);
		//var_dump($res);exit;
		$card_id=$res['card_id'];

		//插入主表信息
		if($card_type=='GROUPON'){
			//团购券
			$into="userid={$sid},card_type='{$card_type}',card_id='{$card_id}',logo_url='{$logo_url}',brand_name='{$brand_name}',code_type='{$code_type}',
			      title='{$title}',sub_title='{$sub_title}',color='{$color}',notice='{$notice}',description='{$description}',
			      type='{$type}',begin_timestamp='{$begin_timestamp}',end_timestampo='{$end_timestamp}',
			      quantity={$quantity},deal_detail='{$deal_detail}'";


		}elseif($card_type=='CASH'){
			//代金券
			$into="userid={$sid},card_type='{$card_type}',card_id='{$card_id}',logo_url='{$logo_url}',brand_name='{$brand_name}',code_type='{$code_type}',
			      title='{$title}',sub_title='{$sub_title}',color='{$color}',notice='{$notice}',description='{$description}',quantity={$quantity},
			      type='{$type}',begin_timestamp='{$begin_timestamp}',end_timestampo='{$end_timestamp}',
			      least_cost='{$least_cost}',reduce_cost='{$reduce_cost}'";
		}elseif($card_type=='DISCOUNT'){
			//折扣券
			$into="userid={$sid},card_type='{$card_type}',card_id='{$card_id}',logo_url='{$logo_url}',brand_name='{$brand_name}',code_type='{$code_type}',
			      title='{$title}',sub_title='{$sub_title}',color='{$color}',notice='{$notice}',description='{$description}',
			      type='{$type}',begin_timestamp='{$begin_timestamp}',end_timestampo='{$end_timestamp}',
			      quantity={$quantity}, discount='{$discount}'";

		}elseif($card_type=='GIFT'){
			//兑换券
			$into="userid={$sid},card_type='{$card_type}',card_id='{$card_id}',logo_url='{$logo_url}',brand_name='{$brand_name}',code_type='{$code_type}',
			      title='{$title}',sub_title='{$sub_title}',color='{$color}',notice='{$notice}',description='{$description}',
			      type='{$type}',begin_timestamp='{$begin_timestamp}',end_timestampo='{$end_timestamp}',
			      quantity={$quantity},gift='{$gift}'";

		}elseif($card_type=='GENERAL_COUPON'){
			//优惠券
			$into="userid={$sid},card_type='{$card_type}',card_id='{$card_id}',logo_url='{$logo_url}',brand_name='{$brand_name}',code_type='{$code_type}',
			      title='{$title}',sub_title='{$sub_title}',color='{$color}',notice='{$notice}',description='{$description}',
			      type='{$type}',begin_timestamp='{$begin_timestamp}',end_timestampo='{$end_timestamp}',
			      quantity={$quantity},default_detail='{$default_detail}'";
		}
		$card_type_id1=$this->setdata("wxcard_baseinfo",$into);
		$into2="baseinfo_id='{$card_type_id1}',can_share='{$can_share}',can_give_friend='{$can_give_friend}',service_phone='{$service_phone}',
				get_limit={$get_limit},use_custom_code='{$use_custom_code}',bind_openid='{$bind_openid}'";
		$card_type_id2=$this->setdata("wxcard",$into2);
		echo "做好了";exit;
		header('location:?g=wx&m=weixin&a=show_card');
	}

	//展示卡券列表
	public function show_card(){
		$sid=$this->userinfo['userid'];  //商户id
		$card_data=$this->arrdata("*","wxcard_baseinfo","where userid={$sid}");
		$this->smarty->assign('card_data',$card_data);
		$this->smarty->display("wx_show_card.tpl");
	}

	//删除卡券信息
	public function del_card(){
		$id=$_GET['id'];
		$sid=$this->userinfo['userid'];  //商户id
		$this->deldata("wxcard_baseinfo","where userid=$sid and id=$id");
		header('location:?g=wx&m=weixin&a=show_card');
	}
}